
package com.hgk.common.common.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.dongqiuhui.apps.comm.tools.FolderOper;
import com.common.dongqiuhui.apps.comm.util.SharedPreferencesUtil;
import com.hgk.common.common.ui.adapter.PicPhotoSelectAdapter;
import com.hgk.common.common.ui.model.PhotosBean;
import com.hgk.common.common.ui.view.RippleView;
import com.hgk.wanwan.photo.PhotoProcessConstants;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import width.hgk.wanwan.R;

public class PicSelectActivity extends BallTitleAcitivty implements OnItemClickListener {

	private GridView mGview;
	private int mSelectCount=1;
	private PhotosBean mCameraBean;
	private ArrayList<PhotosBean> mSList;
	private PicPhotoSelectAdapter mAdapter;
	private ArrayList<String> mPathList;
	private String JPG_SUFFIX = ".jpg";
	private final String DIR_DCIM = "DCIM";
	private final String DIR_CAMERA = "Camera";

	private String sTmpCapture;
	private RippleView mRvConfirm,mRvOk;
	private TextView mTvSelectCount;
	private boolean isConfirm=true;
	private int mFrom;
	public static final int CHAT_PICSELECT=9001;
	public static final int PUBLISH_PLAYING=9002;
	public static final int RESET_HEADPIC=9003;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initView();
		initData();
		new PicImageLoader().execute();
	}
	private void initView(){
		getTitleTv().setBackgroundColor(0x00000000);
		mGview=(GridView)findViewById(R.id.grid_picselect);
		mGview.setOnItemClickListener(this);
		mRvConfirm=(RippleView)findViewById(R.id.rv_confirm);
		mRvOk=(RippleView)findViewById(R.id.rv_ok);
		mTvSelectCount=(TextView)findViewById(R.id.tv_select_count);
		mTvSelectCount.setText("0");
		if(mFrom==CHAT_PICSELECT||mFrom==RESET_HEADPIC){
			mTvSelectCount.setVisibility(View.GONE);
		}
		mRvOk.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
			
			@Override
			public void onComplete(RippleView rippleView) {
				if(mPathList.size()<=0){
					Toast.makeText(mContext, "至少选择一张照片", Toast.LENGTH_SHORT).show();
					return;
				}
				Intent intent = new Intent();
				intent.putStringArrayListExtra(PhotoProcessConstants.EXTRA_PATH_LSIT, mPathList);
				setResult(RESULT_OK, intent);//(resultCode,intent)返回结果带数据
				finish();
			}
		});
		mRvConfirm.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
			
			@Override
			public void onComplete(RippleView rippleView) {
				if(mPathList.size()<=0){
					Toast.makeText(mContext, "至少选择一张照片", Toast.LENGTH_SHORT).show();
					return;
				}
//				PhotoProcessActivity.launch(mContext, mPathList, true, mSelectCount - mPathList.size());
			}
		});
	}
	private void initData(){
		 mSList=new ArrayList<PhotosBean>();
		 mCameraBean=new PhotosBean();
		 mCameraBean.setPic_path("-1");
		 mPathList=new ArrayList<String>();
		 mSelectCount=getIntent().getIntExtra("limit_count", 1);
		 isConfirm=getIntent().getBooleanExtra("is_confirm", true);
		 if(!isConfirm){
			 mRvConfirm.setVisibility(View.GONE);
		 }
	}
	@Override
	public void setLeftButton(RelativeLayout relativeLayout,Button button) {

//		button.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				if(mFrom!=CHAT_PICSELECT&&mFrom!=RESET_HEADPIC){
//					Intent intent = new Intent();
//					intent.putStringArrayListExtra(PublishSkillConstants.EXTRA_PATH_LSIT, mPathList);
//					setResult(RESULT_OK, intent);
//				}
//				finish();
//			}
//		});
	}
	@Override
	public void setRightButton(RelativeLayout relativeLayout,Button button) {
		mFrom =  getIntent().getIntExtra("from", -1);
//		if(mFrom==CHAT_PICSELECT||mFrom==RESET_HEADPIC){
//			button.setVisibility(View.VISIBLE);
//			button.setTextColor(getResources().getColor(R.color.white));
//			if(mFrom==CHAT_PICSELECT){
//				button.setText("发送");
//			}else if(mFrom==RESET_HEADPIC){
//				button.setText("完成");
//			}
//		}else{
//			button.setVisibility(View.GONE);
//		}
//		
//		button.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.putStringArrayListExtra(PublishSkillConstants.EXTRA_PATH_LSIT, mPathList);
//				setResult(RESULT_OK, intent);
//				finish();
//			}
//		});
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
//			if(mFrom!=CHAT_PICSELECT&&mFrom!=RESET_HEADPIC){
//				Intent intent = new Intent();
//				intent.putStringArrayListExtra(PublishSkillConstants.EXTRA_PATH_LSIT, mPathList);
//				setResult(RESULT_OK, intent);
//				finish();
//			}
//			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public Object getTitleString() {
		return "相机胶卷";
	}
	@Override
	public int getBodyView() {
		return R.layout.pic_photo_select;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode==RESULT_OK){
			switch (requestCode) {

			case PhotoProcessConstants.CAMERA_WITH_DATA:
				String path = SharedPreferencesUtil.getStringValue(mContext, "last_capture_path");
				if(!TextUtils.isEmpty(path)){
					PhotosBean bean=new PhotosBean();
					bean.setIs_select(1);
					bean.setPic_path(path);
					mSList.add(1, bean);
					mPathList.add(path);
					mAdapter.notifyDataSetChanged();
					mTvSelectCount.setText(mPathList.size()+"");
				}

			case PhotoProcessConstants.DEL_BIG_PHOTO_CODE:
				mSList.add(mCameraBean);
				break;
			case PhotoProcessConstants.PHOTO_PROCESS_REQUEST_CODE:
				if(data!=null&&data.hasExtra(PhotoProcessConstants.EXTRA_BUNDLE)){
					Bundle bundle=data.getBundleExtra(PhotoProcessConstants.EXTRA_BUNDLE);
					mPathList=bundle.getStringArrayList(PhotoProcessConstants.EXTRA_PATH_LSIT);
					Intent intent = new Intent();
					intent.putStringArrayListExtra(PhotoProcessConstants.EXTRA_PATH_LSIT, mPathList);
					setResult(RESULT_OK, intent);
					finish();
				}
				break;
			default:
				break;
			}
		}
		if(resultCode==RESULT_CANCELED){
			switch (requestCode) {
			case PhotoProcessConstants.PHOTO_PROCESS_REQUEST_CODE:
				finish();
				break;

			default:
				break;
			}
		}
	}
	class PicImageLoader extends AsyncTask<Void, Void, List<PhotosBean>> {

		@Override
		protected List<PhotosBean> doInBackground(Void... params) {
			if (mSList == null) {
				mSList = new ArrayList<PhotosBean>();
			}
			mSList.add(mCameraBean); // 拍照预留
			try {
				Cursor c = BallUtil.getImageQueryCursor(getContentResolver());
				if(c!=null){
					while (c.moveToNext()) {
						String path = c.getString(c.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
						if(!TextUtils.isEmpty(path)){
                            File file=new File(path);
							if(file.exists()){
								PhotosBean bean = new PhotosBean();
								bean.setPic_path(path);
								mSList.add(bean);
							}
						}
					}
					c.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return mSList;
		}
		@Override
		protected void onPostExecute(List<PhotosBean> result) {
			super.onPostExecute(result);
			if(mSList==null||mSList.size()==0){
				Toast.makeText(mContext, "相册里还没有照片哦", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if(mAdapter==null){
				mAdapter = new PicPhotoSelectAdapter(mContext, mSList, mSelectCount);
				mGview.setAdapter(mAdapter);
				mAdapter.notifyDataSetChanged();
			}
		}
		
	}
    //拍摄照片
	public void takePhoto(Activity context) {
		if (FolderOper.isExistSdcard(context)) {
			String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + JPG_SUFFIX;
			String dir = getAlbumsPath();
			File dirFile = new File(dir);
			if (!dirFile.exists()) {
				dirFile.mkdir();
			}
			File tmp = new File(dir, name);
			sTmpCapture = tmp.getPath();
			SharedPreferencesUtil.setValue(context, "last_capture_path", sTmpCapture);
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//相片
//            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);//视频
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tmp));

			context.startActivityForResult(intent,PhotoProcessConstants.CAMERA_WITH_DATA);
		}
	}

	@SuppressLint("NewApi")
	private String getAlbumsPath() {
		if (android.os.Build.VERSION.SDK_INT < 8) {
			return Environment.getExternalStorageDirectory().getAbsolutePath()
					+ File.separator + DIR_DCIM + File.separator + DIR_CAMERA;
		} else {
			return Environment.getExternalStoragePublicDirectory(
					Environment.DIRECTORY_DCIM).getAbsolutePath()
					+ File.separator + DIR_CAMERA;
		}
	}

	public void addPic(int position){
		PhotosBean bean = (PhotosBean) mAdapter.getItem(position);
		if(bean.getIs_select()==0&&mPathList.size()>=mSelectCount){
			Toast.makeText(mContext, "最多选择" + mSelectCount + "张", Toast.LENGTH_SHORT).show();
			return;
		}
//		if(position==0){
//			String status = Environment.getExternalStorageState();
//			if (status.equals(Environment.MEDIA_MOUNTED)) {
//				takePhoto(PicSelectActivity.this);
//			} else {
//				Toast.makeText(getApplicationContext(), R.string.capture_error,Toast.LENGTH_SHORT).show();
//			}
//		}else{
			if(bean!=null){
				if(bean.getIs_select()==0){
					bean.setIs_select(1);
					mPathList.add(TextUtils.isEmpty(bean.getPic_path())?"":bean.getPic_path());
				}else{
					bean.setIs_select(0);
					mPathList.remove(TextUtils.isEmpty(bean.getPic_path())?"":bean.getPic_path());
				}
				mTvSelectCount.setText(mPathList.size()+"");
//				mAdapter.notifyDataSetChanged();
				mAdapter.setImageSelected(bean.getIs_select());
			}
//		}
	}
	//查看图片详情
	public void seePoto(int position){
//		mSList.remove(0);
		if(position==0){
			String status = Environment.getExternalStorageState();
			if (status.equals(Environment.MEDIA_MOUNTED)) {
				takePhoto(PicSelectActivity.this);
			} else {
				Toast.makeText(getApplicationContext(), R.string.capture_error, Toast.LENGTH_SHORT).show();
			}
		}else{
			ImagePreviewActivity.launch(mContext, position-1, null, mSList,false);//本地图片大图
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
	}

	public static void launch(Context context,int limitCount,boolean isRequest,int from){
		Intent intent=new Intent(context,PicSelectActivity.class);
		intent.putExtra("limit_count", limitCount);
		intent.putExtra("from", from);
		if(isRequest){
			((Activity)context).startActivityForResult(intent, PhotoProcessConstants.GET_PATH_LIST_CROP_REQUEST_CODE);//(intent ,requestCode)
		}else{
			context.startActivity(intent);
		}
	}

	public static void launch(Context context,int limitCount,boolean isRequest,boolean isConfirm){
		Intent intent=new Intent(context,PicSelectActivity.class);
		intent.putExtra("limit_count", limitCount);
		intent.putExtra("is_confirm", isConfirm);
		if(isRequest){
			((Activity)context).startActivityForResult(intent, PhotoProcessConstants.GET_PATH_LIST_REQUEST_CODE);
		}else{
			context.startActivity(intent);
		}
	}
}
